package com.cp.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cp.core.mapper.DictMapper;
import com.cp.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ming
 * @create 2022/7/28
 * @description:
 */
@Slf4j
@NoArgsConstructor
public class ExcelDictDtoListener extends AnalysisEventListener<ExcelDictDTO> {
    private DictMapper dictMapper;
    public ExcelDictDtoListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    //为了防止批量操作数据因此建立一个列表减少插入次数
    List<ExcelDictDTO> list = new ArrayList<>();
    static  final  int BATCH_COUNT = 5;
    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext analysisContext) {
       log.info("解析到一条数据:{}",data);
       list.add(data);
       if(list.size()>=BATCH_COUNT){
           saveData(list);
           list.clear();
       }
    }

    private void saveData(List<ExcelDictDTO> list) {
        this.dictMapper.insertBatch(list);
        log.info("{}条数据存储成功",list.size());

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当最后剩余数据不足5条时,最终一次性存储剩余数据
        saveData(list);
        log.info("excel数据解析完毕!");
    }
}
